

package com.zdsx.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zdsx.annotation.Login;
import com.zdsx.common.exception.ErrorCode;
import com.zdsx.common.exception.CommonException;
import com.zdsx.dao.CaffeineRepository;
import com.zdsx.entity.TokenEntity;
import com.zdsx.service.TokenService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;

import static com.zdsx.service.impl.TokenServiceImpl.EXPIRE;
import static com.zdsx.service.impl.TokenServiceImpl.TOKEN_CACHE_NAME;

/**
 * 权限(Token)验证
 *
 * @author Lr
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private TokenService tokenService;

    @Resource
    private CaffeineRepository caffeineRepository;

    @Value("${spring.profiles.active: dev}")
    private String env;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }

        //token为空
        if (StrUtil.isBlank(token)) {
            throw new CommonException(ErrorCode.TOKEN_NOT_EMPTY);
        }

        // 查询token信息: 先从缓存中获取token，然后再从db获取
        TokenEntity tokenEntity = caffeineRepository.getExpire(TOKEN_CACHE_NAME, token, TokenEntity.class);
        if (tokenEntity == null) {
            tokenEntity = tokenService.getByToken(token);
        }

        // 查询token信息: token为空，或者token已经超过有效期了
        if (tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
            throw new CommonException(ErrorCode.TOKEN_INVALID);
        }

        // 获取当前有效期，如果有效期小于半小时，则重置有效期
        long seconds = (tokenEntity.getExpireDate().getTime() - System.currentTimeMillis()) / 1000;
        if (seconds < EXPIRE / 1000 / 2) {
            Date expireTime = new Date(new Date().getTime() + EXPIRE * 1);
            // token续期为1小时
            tokenEntity.setExpireDate(expireTime);
            tokenService.updateToken(tokenEntity);
            caffeineRepository.setExpire(TOKEN_CACHE_NAME, token, tokenEntity, EXPIRE / 1000);
        } else {
            caffeineRepository.setExpire(TOKEN_CACHE_NAME, token, tokenEntity, seconds);
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, tokenEntity.getUserId());

        return true;
    }
}
